package com.tanhua.server.serivce;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private UserStatusService userStatusService;

    /**
     * 查询动态的评论列表
     *    根据动态id和互动类型（2）
     */
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //1、调用API查询评论数据：List<Comment>
        Integer commentType = 2;
        List<Comment> list = commentApi.findComments(page,pagesize,movementId,commentType);
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);//所有评论人id
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //2、将List<Comment>转化为List<CommentVo>
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            UserInfo userInfo = map.get(comment.getUserId());//
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        //3、构造返回值
        return new PageResult(page,pagesize,0l,vos);
    }

    /**
     * 保存评论
     * @param movementId  动态id
     * @param content 评论内容
     */
    public void saveComment(String movementId, String content) {
        //获取用户id
        Long userId = UserHolder.getUserId();
        //根据UserId查询用户信息
        User user = userApi.findById(userId);
        //判断该用户的评论权限是否被冻结,如果被冻结,抛出评论冻结异常
        Boolean commentFreeze = userStatusService.findCommentFreeze(user);
        if (commentFreeze){
            throw new BusinessException(ErrorResult.freezeCommentError());
        }
        //1、创建Comment对象
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(2);
        comment.setContent(content);
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        //没有设置动态发布人
        //2、调用api保存，返回评论总数
        Integer count = commentApi.save(comment);
        System.out.println("发布之后的评论总数="+count);
    }
}
